//
//  KeychainHelper.swift
//  Tala
//
//  Created by 千策万划-mini on 2025/4/29.
//

import Foundation
import Security
import UIKit

class KeychainHelper {
    static let keychainService = "com.pesogrants.keychain"
    static let keychainIDFVKey = "device_idfv"

    /// 获取IDFV（如钥匙串无则自动保存）
    static func getIDFVFromKeychain() -> String {
        // 查询钥匙串
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: keychainService,
            kSecAttrAccount as String: keychainIDFVKey,
            kSecReturnData as String: kCFBooleanTrue!,
            kSecMatchLimit as String: kSecMatchLimitOne
        ]

        var result: AnyObject?
        let status = SecItemCopyMatching(query as CFDictionary, &result)

        if status == errSecSuccess, let data = result as? Data, let idfv = String(data: data, encoding: .utf8) {
            return idfv
        } else {
            // 钥匙串无，获取新的IDFV并保存
            let newIDFV = UIDevice.current.identifierForVendor?.uuidString ?? UUID().uuidString
            saveIDFVToKeychain(newIDFV)
            return newIDFV
        }
    }

    /// 保存IDFV到钥匙串
    static func saveIDFVToKeychain(_ idfv: String) {
        guard let idfvData = idfv.data(using: .utf8) else { return }

        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: keychainService,
            kSecAttrAccount as String: keychainIDFVKey
        ]

        let attributesToUpdate: [String: Any] = [
            kSecValueData as String: idfvData
        ]

        let status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary)

        if status == errSecItemNotFound {
            // 不存在则添加
            var newItem = query
            newItem[kSecValueData as String] = idfvData
            let addStatus = SecItemAdd(newItem as CFDictionary, nil)
            if addStatus != errSecSuccess {
                print("保存IDFV到钥匙串失败，错误码：\(addStatus)")
            }
        } else if status != errSecSuccess {
            print("保存IDFV到钥匙串失败，错误码：\(status)")
        }
    }
}
